<script setup>
import * as echarts from 'echarts';
import petApi from '../api/pet_api.js';
import { ref, onMounted, watch } from 'vue';
import {
  ElIcon, ElTag, ElPopover, ElButton, ElTable, ElTableColumn,
  ElMessageBox, ElMessage, ElSelect, ElOption, ElForm, ElFormItem,
  ElInput, ElDatePicker, ElDialog, ElPagination
} from 'element-plus';
import { Picture, Timer, Warning } from '@element-plus/icons-vue';
import lodash from 'lodash';

// 存储宠物类型统计数据
const petKindData = ref([]);
// 图表实例
let myChart = null;

// 初始化图表
const initChart = () => {
  // 获取DOM元素
  const chartDom = document.getElementById('petKindChart');
  // console.log(chartDom);
  if (!chartDom) return;

  // 初始化图表实例
  myChart = echarts.init(chartDom);
  // console.log(myChart);

  // 设置图表配置
  const option = {
    title: {
      text: '宠物类型分布',
      subtext: '各类型宠物数量统计',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '宠物类型',
        type: 'pie',
        radius: '50%',
        data: petKindData.value,
        // data: [
        //   { value: 1048, name: 'Search Engine' },
        //   { value: 735, name: 'Direct' },
        //   { value: 580, name: 'Email' },
        //   { value: 484, name: 'Union Ads' },
        //   { value: 300, name: 'Video Ads' }
        // ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };
console.log(option);
  // 设置配置项
  myChart.setOption(option);

  // 监听窗口大小变化，自动调整图表大小
  window.addEventListener('resize', () => {
    if (myChart) {
      myChart.resize();// 重新设置图表大小
    }
  });
};

// 加载宠物类型数据
const loadPetKindData = async () => {
  try {
    const response = await petApi.countPetKind();
    console.log(response);
    // { "猫": 10, "狗": 20 }这样的对象
    const transformedData = [];
    for (const key in response) {
      if (response.hasOwnProperty(key)) {
        transformedData.push({ name: key, value: response[key].count });
      }
    }
    petKindData.value = transformedData;
    console.log(petKindData.value);
  } catch (error) {
    ElMessage.error('获取宠物类型数据失败: ' + (error.message || '未知错误'));
    console.error(error);
  }
};

// 当组件挂载时初始化
onMounted(() => {
  // 先加载数据，再初始化图表
  loadPetKindData().then(() => {
    initChart();
  });
});

// 监听数据变化，实时更新图表
watch(petKindData, (newVal) => {
  if (myChart && newVal) {
    myChart.setOption({
      series: [
        {
          data: newVal
        }
      ]
    });
  }
});
</script>

<template>
<!--  {{petKindData}}-->
  <!-- 图表容器，需要设置宽高才能显示 -->
  <div class="chart-container">
    <div id="petKindChart" class="chart"></div>
  </div>
</template>

<style scoped>
.chart-container {
  width: 100%;
  min-width: 300px;
  height: 100%;
  min-height: 400px;
  padding: 20px;
}

.chart {
  width: 100%;
  height: 100%;
}
</style>
